package com.rainwen.shiro.controller;

import com.rainwen.shiro.constant.ContextConstants;
import com.rainwen.shiro.entity.SysUser;
import com.rainwen.shiro.service.SysResourceService;
import com.rainwen.shiro.vo.ResourcePermissionVO;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;

/**
 *
 * @author rain.wen
 * @date 2017/8/9
 */
@Controller
public class LoginController extends BaseController {

    private final static String SUCCESS = "/home";

    private final static String LOGIN = "/login";

    @Autowired
    private SysResourceService sysResourceService;

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {
        return "login";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        ModelMap modelMap,
                        HttpSession session) {
        Subject subject = SecurityUtils.getSubject();
        String result = "redirect:/home";
        String loginResult = "";
        if (!subject.isAuthenticated()) {
            loginResult = login(subject, username, password);
        } else {//重复登录
            SysUser user = (SysUser) subject.getPrincipals().asList().get(1);
            if (!user.getUsername().equalsIgnoreCase(username)) {
                subject.logout();
                loginResult = login(subject, username, password);
            }
        }
        if(loginResult != null && loginResult.length() > 0) {
            modelMap.addAttribute("errorMsg", loginResult);
            result = LOGIN;
        } else {
            Integer userId = getUserId();
            ResourcePermissionVO resourcePermissionVO = sysResourceService.findMenuResourceByUserId(userId);

            session.setAttribute(ContextConstants.SESSION_RESOURCE, resourcePermissionVO.getResourceVOList());
            session.setAttribute(ContextConstants.SESSION_URL_PERMISSION, resourcePermissionVO.getUrlPermissionMap());
        }
        return result;
    }

    private String login(Subject subject, String username, String password) {
        String result = null;
        UsernamePasswordToken token = new UsernamePasswordToken(username,
                password);
        token.setRememberMe(false);
        try {
            subject.login(token);
            return result;
        } catch (UnknownAccountException uae) {
            uae.printStackTrace();
            result = "账号不存在";
        } catch (IncorrectCredentialsException ice) {
            ice.printStackTrace();
            result = "账号或密码错误";
        } catch (LockedAccountException lae) {
            lae.printStackTrace();
            result = "账号锁定";
        } catch (AuthenticationException ae) {
            ae.printStackTrace();
            result = "账号或密码错误";
        }
        return result;
    }

    @RequestMapping(value = "/logout")
    public String logout() {
        SecurityUtils.getSubject().logout();
        return "/login";
    }

}
